<template>
  <div>
    <!-- 面包屑 -->
    <Breadcrumb :crumbs='crumbs'/>
    <!-- 数据区域 -->
    <el-card class="box-card">
      <!-- 搜索区 -->
      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="primary" @click="handleAddRoleBtn">添加角色</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-table stripe style='width:100%' :data="roles">
          <el-table-column type="expand">
            <template v-slot='scope'>
              <el-row :class="['expendRowCenter', 'expendColumnBt', index === 0 ?'expendColumnTp': '']"
               :gutter="20" :key="item.id" v-for="(item, index) in scope.row.children">
                <el-col :span="5">
                  <el-tag @close='handleExpendRoleDelete(scope.row, item.id)' closable>{{ item.authName }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <el-row :class="['expendRowCenter', index2 === 0 ?'': 'expendColumnTp']" :key="item2.id" v-for="(item2, index2) in item.children">
                    <el-col :span="6">
                      <el-tag @close='handleExpendRoleDelete(scope.row, item2.id)' closable type="success">{{ item2.authName }}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag @close='handleExpendRoleDelete(scope.row, item3.id)'
                       closable type="warning" :key='item3.id' v-for="item3 in item2.children">{{ item3.authName }}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column prop="" label="操作">
            <template slot-scope="scope">
              <el-button @click="handleEditBtn(scope.row)" class="el-icon-edit" size="mini" type="primary">编辑</el-button>
              <el-button @click="handleDeleteBtn(scope.row)" class="el-icon-delete" size="mini" type="danger">删除</el-button>
              <el-button @click="handlePermissionBtn(scope.row)" class="el-icon-setting" size="mini" type="warning">分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-card>
    <!-- 添加/修改角色弹框 -->
    <el-dialog width="30%"
      :title="dialogType === 1? '添加角色':'修改角色'"
      :visible.sync="dialogVisible">
      <el-form ref="roleForm" :model="formData" :rules="formRules">
        <el-form-item label="角色名称" prop="roleName" label-width="80px">
          <el-input v-model="formData.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" label-width="80px">
          <el-input v-model="formData.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleDialogSaveRole">确认</el-button>
      </template>
    </el-dialog>
    <!-- 分配权限弹框 -->
    <el-dialog width="30%"
      title="分配权限"
      :visible.sync="permissionDialogVisible">
      <el-tree ref="authTree" :data="treeData" show-checkbox
        node-key='id'
        default-expand-all
        :default-checked-keys="defaultCheckedKeys"
        :props="defaultProps"></el-tree>
      <template v-slot:footer>
        <el-button @click="permissionDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleDialogSavePermission">确认</el-button>
      </template>
      </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from '../Breadcrumb.vue'

export default {
  components: { Breadcrumb },
  data () {
    return {
      crumbs: [
        { path: '/home', title: '首页' },
        { title: '权限管理' },
        { title: '角色列表' }
      ],
      roles: [],
      dialogVisible: false,
      dialogType: 1,
      formData: {},
      formRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度为2～10位', trigger: 'blur' }
        ],
        roleDesc: []
      },
      permissionDialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      defaultCheckedKeys: [],
      treeData: [],
      savePermissionRoleId: ''
    }
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.axios.get('private/v1/roles')
      console.log('getRolesList res:', res)
      if (!res || !res.meta || res.meta.status !== 200) return this.$message.error('获取角色失败')
      this.roles = res.data
    },
    async getAllRights () {
      // 获取所有权限
      const { data: res } = await this.axios.get('private/v1/rights/tree')
      console.log('getAllRights res:', res)
      if (!res || !res.meta || res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.treeData = res.data
    },
    getLeafKeys (auth) {
      // 获取叶子节点的 key
      const permissions = auth.children
      let leafKeys = []
      if (!permissions || permissions.length <= 0) {
        leafKeys.push(auth.id)
        return leafKeys
      }
      permissions.forEach(per => {
        leafKeys = leafKeys.concat(this.getLeafKeys(per))
      })
      return leafKeys
    },
    async handleExpendRoleDelete (row, rightId) {
      // 处理展开项里的权限删除
      console.log(row.id, rightId)
      const confirmRes = await this.$confirm('确认删除当前权限吗？', '权限删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).catch(action => action)
      if (confirmRes !== 'confirm') return
      const { data: res } = await this.axios.delete(`/private/v1/roles/${row.id}/rights/${rightId}`)
      if (!res || !res.meta || res.meta.status !== 200) return this.$message.error('删除权限失败')
      this.$message.success('删除权限成功')
      row.children = res.data
    },
    handleAddRoleBtn () {
      this.dialogVisible = true
      this.dialogType = 1
      if (this.$refs.roleForm) this.$refs.roleForm.resetFields()
    },
    handleEditBtn (role) {
      this.dialogVisible = true
      this.dialogType = 2
      if (this.$refs.roleForm) this.$refs.roleForm.resetFields()
      this.formData = {
        id: role.id,
        roleName: role.roleName,
        roleDesc: role.roleDesc
      }
    },
    async handleDialogSaveRole () {
      // 添加/修改 弹框保持按钮处理
      if (this.dialogType === 1) {
        const { data: res } = await this.axios.post('/private/v1/roles', this.formData)
        console.log('handleDialogSaveRole:', res)
        if (!res || !res.meta || res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
      } else {
        const { data: res } = await this.axios.put(`/private/v1/roles/${this.formData.id}`, this.formData)
        if (!res || !res.meta || res.meta.status !== 200) return this.$message.error('修改角色失败')
        this.$message.success('修改角色成功')
      }
      this.dialogVisible = false
      this.getRolesList()
    },
    async handleDeleteBtn (role) {
      // 删除角色按钮处理
      const confirmRes = await this.$confirm('确认删除当前角色吗？', '删除角色', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).catch(act => act)
      if (confirmRes !== 'confirm') return
      const { data: res } = await this.axios.delete(`/private/v1/roles/${role.id}`)
      if (!res || !res.meta || res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    handlePermissionBtn (role) {
      // 分配权限弹框
      this.permissionDialogVisible = true
      this.savePermissionRoleId = role.id
      this.getAllRights()
      this.defaultCheckedKeys = this.getLeafKeys(role)
      console.log('defaultCheckedKeys:', this.defaultCheckedKeys)
    },
    async handleDialogSavePermission () {
      // 保持更新后的权限
      let keys = []
      keys = keys.concat(this.$refs.authTree.getCheckedKeys())
      keys = keys.concat(this.$refs.authTree.getHalfCheckedKeys())
      console.log('checked keys:', keys)
      const params = { rids: keys.join(',') }
      const { data: res } = await this.axios.post(`/private/v1/roles/${this.savePermissionRoleId}/rights`, params)
      if (!res || !res.meta || res.meta.status !== 200) return this.$message.error('修改权限失败')
      this.$message.success('修改权限成功')
      this.permissionDialogVisible = false
      this.getRolesList()
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
.box-card {
  margin: 10px;
}

.expendColumnBt {
  border-bottom: 1px solid #eee;
}

.expendColumnTp {
  border-top: 1px solid #eee;
}

.expendRowCenter {
  display: flex;
  align-items: center;
}

</style>
